import { createApp } from 'vue'
import ToastContainer from './ToastContainer.vue'

interface ToastOptions {
  message?: string
  duration?: number
}

class ToastManager {
  private toastInstance: any = null
  private container: HTMLElement | null = null

  private createContainer() {
    if (!this.container) {
      this.container = document.createElement('div')
      this.container.id = 'toast-root'
      document.body.appendChild(this.container)
    }
    return this.container
  }

  show(options: ToastOptions = {}) {
    const { message = '操作成功', duration = 2000 } = options

    // 如果已有实例，先销毁
    if (this.toastInstance) {
      this.hide()
    }

    const container = this.createContainer()

    // 创建 Vue 应用实例
    const app = createApp(ToastContainer, {
      message,
      duration,
    })

    const vm = app.mount(container)
    this.toastInstance = {
      vm,
      app,
    }
    this.toastInstance.vm.show()
  }

  hide() {
    if (this.toastInstance) {
      this.toastInstance.vm.hide()
      this.toastInstance.app.unmount()
      this.toastInstance = null
    }
    if (this.container) {
      document.body.removeChild(this.container)
      this.container = null
    }
  }
}

const toastManager = new ToastManager()

// 导出函数式调用方法
export const showToast = (options: ToastOptions | string) => {
  if (typeof options === 'string') {
    toastManager.show({ message: options })
  } else {
    toastManager.show(options)
  }
}

export const hideToast = () => {
  toastManager.hide()
}

// 便捷方法
export const toast = {
  success: (message: string = '操作成功') => showToast({ message }),
  error: (message: string = '操作失败') => showToast({ message }),
  info: (message: string = '提示信息') => showToast({ message }),
  show: showToast,
  hide: hideToast,
}

export default toast
